# coding:utf-8
import datetime
import json
import os
import time
import csv

from selenium import webdriver
from selenium.webdriver.common.by import By
from loguru import logger
import requests
from toollib import autodriver
from excel import Excel

path = os.path.abspath("./log")
log_path = os.path.join(path, f"{datetime.date.today()}.txt")
logger.add(sink=log_path, rotation="00:00", encoding="utf-8")


def logging(funcDesc=None):  # 用于装饰的函数名
    def outwrapper(func):  # 接收 用于调用的函数名
        def wrapper(*args, **kwargs):  # 接收 传递到调用函数的参数
            logger.info(f"{funcDesc},调用:{func.__name__}()")
            logger.info(f"请求参数:{args} {kwargs}")
            returnData = func(*args, **kwargs)  # 调用被装饰的函数
            logger.debug(f"{'返回数据'}:{returnData}")
            return returnData

        return wrapper

    return outwrapper

class CreatUser:
    def __init__(self, url=None):
        """自动化oa登陆获取 获取cookie并保存"""
        cookieTime = ''
        try:
            with open("../cookie.json", "r") as data:  # 获取保存的cookie
                cookieData = json.loads(data.read())
                cookieTime = cookieData["time"]
                self.cookie = cookieData["cookie"]
        except:
            logger.debug("获取cookie.txt信息失败")

        if str(datetime.date.today()) != cookieTime:  # 判断 是否 属于今天的cookie
            logger.debug("cookie已过期，重新获取cookie")
            options = webdriver.ChromeOptions()
            options.add_argument('headless')
            try:
                browser = webdriver.Chrome(executable_path=autodriver.chromedriver(), options=options)
            except:
                raise Exception("chromedriver驱动不存在或版本不一致，请使用与Chrome浏览器版本一致的chromedriver驱动")
            browser.implicitly_wait(5)
            browser.get("https://xuat.wxp.woa.com/assistant/caseInputManagement")
            browser.find_element(By.ID, "btn_smartlogin").click()  # oa登录
            time.sleep(1)

            cookies = browser.get_cookies()
            cookie_list = [(i["name"] + "=" + i["value"]) for i in cookies]
            self.cookie = ";".join(cookie_list)

            with open("../cookie.json", "w") as data:
                data.write(json.dumps({"time": str(datetime.date.today()), "cookie": self.cookie}))
            logger.debug("已成功获取cookie，并保存")
            browser.quit()

    @logger.catch
    def post_uat(self, url, data):
        """往uat系统发送请求"""
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json, text/plain, */*',
            "Cookie": self.cookie,
            "Host": "xuat.wxp.woa.com",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62",
        }
        re = requests.post(url, data=data, headers=headers)
        return re.json()

    @logger.catch
    def get_uat(self, url):
        """往uat系统发送请求"""
        headers = {
            "Cookie": self.cookie,
            "Host": "xuat.wxp.woa.com",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62",
        }
        re = requests.get(url, headers=headers)
        return re.json()


class Operation(CreatUser):

    # """获取所有 验收中的 资源工单(可测性api,用户组,商户组)"""
    @logger.catch
    @logging("获取所有 验收中的 资源工单(可测性api,用户组,商户组)")
    def getResources(self, baseLineId):
        self.baseLineId = baseLineId
        urlDict = {
            '可测性api':"https://xuat.wxp.woa.com/apis/v1/statistics/getTestAbilityApiListInfo",
            '商户组':"http://xuat.wxp.woa.com/apis/v1/statistics/getMchGroupListInfo",
            '用户组':"http://xuat.wxp.woa.com/apis/v1/statistics/getUserGroupListInfo",
            '优惠组':"https://xuat.wxp.woa.com/apis/v1/statistics/getFavGroupListInfo",
        }
        data = {'scriptBuildingBaseLineId': self.baseLineId, 'pageNum': 1, 'pageSize': 1000, 'scrpitNumSortFlag': 1}
        scriptDict = []
        for item in urlDict.keys():

            re = self.post_uat(urlDict[item], json.dumps(data))
            dat = re["data"]["resourceList"]
            for i in dat:
                if i['stateId'] == 43:
                    i['nametype'] = item + '-待分配'
                    scriptDict.append(i)
                elif i['stateId'] == 35:
                    i['nametype'] = item + '-处理中'
                    scriptDict.append(i)
                elif i['stateId'] == 44:
                    i['nametype'] = item + '-验收中'
                    scriptDict.append(i)
                elif i['stateId'] == 36:
                    i['nametype'] = item + '-挂起'
                    scriptDict.append(i)
                elif i['stateId'] == 38:
                    i['nametype'] = item + '-撤销'
                    scriptDict.append(i)
                elif i['stateId'] == 79:
                    i['nametype'] = item + '-被驳回'
                    scriptDict.append(i)
        return scriptDict

    # """获取处理完成的问题工单,关联的挂起脚本工单数量"""
    @logger.catch
    @logging("获取处理完成的问题工单")
    def getfindIssueWorkOrderRelatedStatics(self, baseLineId):
        url = 'http://xuat.wxp.woa.com/apis/v1/statistics/findIssueWorkOrderRelatedStatics'
        re = self.post_uat(url, json.dumps({"typeList":[],"stateList":[37,38],"baseLineId":baseLineId,"pageNum":1,"pageSize":1000}))
        dataList = []
        data = re["data"]["workOrderList"]
        for i in data:
            if i['stateId'] == 37:
                workOrderId = i['workOrderId']
                workOrderIdUrl = f'http://xuat.wxp.woa.com/assistant/workOrderDetail/orderTypeId/orderStateId?baseLineId={baseLineId}&workOrderId={workOrderId}'


                url = f'http://xuat.wxp.woa.com/apis/v1/featurebaseline/getScriptBuildingWorkOrdersByIssueWorkOrder?pageSize=100&pageNum=1&workOrderId={workOrderId}'
                re = self.get_uat(url)
                dat = re["data"]["workOrderList"]
                workOrderIdData = []
                for j in dat:
                    if j['workOrderStateId'] == 36:
                        workOrderIdData.append(j['workOrderDebugger'] + '-' + str(j['workOrderId']))
                dataList.append([workOrderIdUrl, len(workOrderIdData), '\n'.join(workOrderIdData)])

        with open("issueWorkOrder.csv", "w", newline="", encoding="utf8") as csvFile:
            csvFileWriter = csv.writer(csvFile)
            csvFileWriter.writerow(['已完成问题工单Url', '关联的本基线挂起工单数量'])
            for data in dataList:
                csvFileWriter.writerow(data)

    # """获取资源工单关联的 未分配的脚本工单数量"""
    @logger.catch
    @logging("获取资源工单关联的 未分配的脚本工单数量")
    def getScript(self, workOrderData):
        dataList = []
        num = 1
        for i in workOrderData:
            logger.debug(f"剩余{len(workOrderData)-num}个，{i}")
            num += 1
            url = f'http://xuat.wxp.woa.com/apis/v1/featurebaseline/getScriptBuildingWorkOrdersByTestResourceWorderOrder?pageSize=500&pageNum=1&testResourceWorkOrderId={i["workOrderId"]}'
            logger.debug(f"url：{url}")
            re = self.get_uat(url)
            dat = re["data"]["workOrderList"]
            dattotallist = []
            datlist = []
            for dati in dat:
                if dati['baselineId'] == self.baseLineId:
                    dattotallist.append(dati)
                    if dati['workOrderStateId'] == 43:
                        datlist.append(dati)
            dataList.append([i["nametype"], i["workOrderId"],len(dattotallist),len(datlist), i["workOrderDetailUrl"], i["desc"], i["workOrderHandler"]])
        return dataList

    # """获取自己名下所有脚本调试工单"""
    @logger.catch
    @logging("获取自己名下所有脚本调试工单")
    def getTodoWorkOrderByBaselineAndHandler(self, baseLineId):
        url = 'http://xuat.wxp.woa.com/apis/v1/workspace/getTodoWorkOrderByBaselineAndHandler'
        datajson01 = {"handler": "v_xboxiao", "pageSize": 10000, "pageNum": 1, "navigationType": "script", "sortField": "groupKey",
         "stateId": 35, "baselineID": baseLineId}
        datajson02 = {"handler": "v_xboxiao", "pageSize": 10000, "pageNum": 1, "navigationType": "script", "sortField": "groupKey",
         "stateId": 79, "baselineID": baseLineId}
        workOrderDataList01 = self.post_uat(url,json.dumps(datajson01))['data']['workOrderList']
        workOrderDataList02 = self.post_uat(url,json.dumps(datajson02))['data']['workOrderList']
        workOrderDataList = workOrderDataList01 + workOrderDataList02
        workOrderList = []
        for i in workOrderDataList:
            workOrderList.append([i['workOrderId'],
                                  i['typeEntityId'],
                                  f"http://xuat.wxp.woa.com/workspace/workOrderDetail/85/35?baseLineId={baseLineId}&workOrderId={i['workOrderId']}&scriptId={i['typeEntityId']}&activeIndex=1",
                                  i['workOrderDesc'],
            ])
        return workOrderList

    # """获取所有生效的商户组"""
    @logger.catch
    @logging("获取所有生效的商户组")
    def getfindMchGroup(self):
        url = 'https://xuat.wxp.woa.com/apis/v1/featurebaseline/findMchGroup'
        datajson = {"pageSize": 1000, "pageNum": 1, "keyWordsType": "feature", "stateId": [14]}
        mchGroupList = self.post_uat(url,json.dumps(datajson))['data']['mchGroupList']
        mchGroupIdList = [item['mchGroupId'] for item in mchGroupList]

        url = 'https://xuat.wxp.woa.com/apis/v1/featurebaseline/findMchGroupAccountList'
        mchidlist = []
        for mchGroupId in mchGroupIdList:
            time.sleep(0.15)
            datajson = {'mchGroupId': mchGroupId, 'pageSize': 500, 'pageNum': 1}
            rep = self.post_uat(url,json.dumps(datajson))['data']['mchAccountList']
            [mchidlist.append(item.values()) for item in rep]
        return mchidlist

    # """转移脚本工单，并设置备注"""
    @logger.catch
    @logging("转移脚本工单，并设置备注")
    def assginWorkOrdersToHandler(self, name, workOrderId, workOrderDesc):
        url = 'http://xuat.wxp.woa.com/apis/v1/featurebaseline/assginWorkOrdersToHandler'
        datajson = {"handler":name,"workOrderIdList":[workOrderId],"workOrderDesc":str(workOrderDesc)}
        self.post_uat(url,json.dumps(datajson))

    # 获取 或 保存 脚本工单数据
    @logger.catch
    @logging('获取 或 保存 脚本工单数据')
    def get_scriptcsv(self, dataListList=None):
        if dataListList:
            excel = Excel('scriptworkOrder.xlsx')
            dataListList.insert(0,['工单ID', '脚本ID', '工单链接', '备注'])
            excel.newWriteData(dataListList)
        else:
            excel = Excel('scriptworkOrder.xlsx')
            oldDataList = excel.gainFormData()
            dataDict= {}
            for i in oldDataList:
                if len(i) == 0:  # 空表格会报错，判断是否处于极端情况
                    return dataDict
                dataDict[i[0]] = i
            return dataDict

    # 保存 资源工单数据
    @logger.catch
    @logging('保存 资源工单数据')
    def get_csv(self, dataList, fileName='Baseline'):
        with open(f"{fileName}{baseLineId}.csv", "w", newline="", encoding="utf8") as csvFile:
            csvFileWriter = csv.writer(csvFile)
            csvFileWriter.writerow(['资源分类', '工单号', '关联总数', '关联脚本数', '工单链接', '描述', '负责人'])    # 写入第一行数据：标题
            for data in dataList:
                logger.debug(f"{data}")
                csvFileWriter.writerow(data)

    # 获取 web端和csv端的脚本工单数据，并按照csv备注修改web端工单备注，最后将web和csv两端的最新数据保存到csv中
    def webcsvscriptworkOrder(self, baseLineId, name):
        webdata = self.getTodoWorkOrderByBaselineAndHandler(baseLineId)
        csvdata = self.get_scriptcsv()
        workOrderIdList = csvdata.keys()
        for webdataItem in webdata:
            print('webdataItem:', webdataItem)
            if webdataItem[0] in workOrderIdList and webdataItem[-1] != csvdata[webdataItem[0]][-1] and csvdata[webdataItem[0]][-1] != None:
                webdataItem[-1] = csvdata[webdataItem[0]][-1]
                self.assginWorkOrdersToHandler(name, webdataItem[0], webdataItem[-1])
        print('webdata:',webdata)
        self.get_scriptcsv(webdata)


def getScript_start(baseLineId):
    op = Operation()
    dataList = op.getResources(baseLineId)
    dataList = op.getScript(dataList)
    op.get_csv(dataList)

if __name__ == '__main__':
    op = Operation()
    #  对应的基线id
    baseLineId = 180

    # 获取当前基线 所有 待分配，处理中，验收中的资源工单
    dataList = op.getResources(baseLineId)
    dataList = op.getScript(dataList)
    op.get_csv(dataList)

    # dataList = op.getfindMchGroup()
    # op.get_csv(dataList)


    # 获取处理完成的问题工单,关联的挂起脚本工单数量
    # op.getfindIssueWorkOrderRelatedStatics(baseLineId)

    # 获取 web端和csv端的脚本工单数据，并按照csv备注修改web端工单备注，最后将web和csv两端的最新数据保存到csv中
    # op.webcsvscriptworkOrder(baseLineId,name)

